import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:yysk_app/business/collection_item_widget.dart';
import 'package:yysk_app/model/tab_model.dart';
import 'package:yysk_app/pages/main/home/banner_widget.dart';
import 'package:yysk_app/pages/main/home/invited_widget.dart';
import 'package:yysk_app/pages/main/home/newcomer_handbook_page.dart';
import 'package:yysk_app/pages/main/main_controller.dart';
import 'package:yysk_app/pages/main/mine/mine_page_controller.dart';
import 'package:yysk_app/pages/nft_pages/home_pages/announcement/announcement_page.dart';
import 'package:yysk_app/pages/nft_pages/home_pages/news_detail/news_detail_page.dart';
import 'package:yysk_app/pages/nft_pages/my_friend/my_friend_page.dart';
import 'package:yysk_app/pages/nft_pages/setting/customer_service/customer_service_page.dart';
import 'package:yysk_app/routes/global_controller.dart';
import 'package:yysk_app/utils/colors.dart';
import 'package:yysk_app/utils/helper.dart';
import 'package:yysk_app/widget/empty_widget.dart';
import 'package:yysk_app/widget/image_asset_widget.dart';
import 'package:yysk_app/widget/loading_container.dart';
import 'package:yysk_app/widget/tab_widget.dart';
import 'package:yysk_app/widget/vertical_scroll_noticebar_widget.dart';
import 'package:oktoast/oktoast.dart';

class HeaderDelegate extends SliverPersistentHeaderDelegate {
  @override
  double get minExtent => 50 +MediaQuery.of(Get.context!).padding.top;

  @override
  double get maxExtent => 50 +MediaQuery.of(Get.context!).padding.top;

  @override
  Widget build(
    BuildContext context,
    double shrinkOffset,
    bool overlapsContent,
  ) {
        double top = MediaQuery.of(context).padding.top;
    return Container(
      color: Color.fromRGBO(0, 0, 0, (shrinkOffset / maxExtent)),
      padding: EdgeInsets.fromLTRB(16.px, top, 16.px, 6),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          ImageAssetWidget(
            imageUrl: 'static/images/home/home_icon.png',
            width: 91.px,
            height: 32.px,
          ),
        ],
      ),
  
    );
  }

  @override
  bool shouldRebuild(SliverPersistentHeaderDelegate oldDelegate) {
    return false;
  }
}

class HeaderDelegate2 extends SliverPersistentHeaderDelegate {
  @override
  double get minExtent => 50.px;

  @override
  double get maxExtent => 50.px;

  @override
  Widget build(
    BuildContext context,
    double shrinkOffset,
    bool overlapsContent,
  ) {
    final MainController controller = Get.find();
    void onChange2(String value) {
      // controller.modeType.value = value;
      controller.selectType.value = value;
      controller.getProductList();
    }

    return Container(
      color:
          overlapsContent ? AppColors.backgroundColorBlack : Colors.transparent,
      child: Padding(
        padding: EdgeInsets.fromLTRB(12.px, 0, 12.px, 0),
        child: Column(
          children: [
            TabWidget(
              isCurrentFontSize: 18,
              notCurrentFontSize: 16,
              tabColor: AppColors.fontColorGreenA9,
              activeColor: AppColors.fontColor,
              currentUndelineColorStart: Color.fromRGBO(0, 234, 255, 1),
              currentUndelineColorEnd: Color.fromRGBO(0, 193, 242, 0.06),
              currentUndeline: true,
              tabList: [
                TabModel(code: 'PLATFORM', label: '平台首发'),
                TabModel(code: 'BRAND', label: '企业首发'),
              ],
              onChanged: onChange2,
            ),
          ],
        ),
      ),
    );
  }

  @override
  bool shouldRebuild(SliverPersistentHeaderDelegate oldDelegate) {
    return false;
  }
}

class HomePage extends StatefulWidget {
  const HomePage({super.key});

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  final MainController controller = Get.find();
  final ScrollController scrollController = ScrollController();
  final GlobalController globalController = Get.find();

  @override
  void initState() {
    super.initState();
    Get.put(MinePageController());
    scrollController.addListener(() {
      if (scrollController.position.pixels ==
          scrollController.position.maxScrollExtent) {
        controller.getProductList(loadMore: true);
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    //获取刘海屏Top安全边距
    double top = MediaQuery.of(context).padding.top;
    return Scaffold(
      body: Obx(
        () => Stack(
          children: [
            Padding(
              padding: EdgeInsets.fromLTRB(0.px, 0, 0.px, 0),
              child: LoadingContainer(
                isLoading: false,
                child: RefreshIndicator(
                  backgroundColor: Colors.transparent,
                  color: Colors.white,
                  onRefresh: _handleRefresh,
                  child: Container(
                    decoration: BoxDecoration(
                      color: AppColors.backgroundColorBlack,
                    ),
                    child: Stack(
                      children: [
                        SizedBox(
                          width: context.width,
                          child: ImageAssetWidget(
                            width: 375.px,
                            height: 812.px,
                            imageUrl: 'static/images/bg.png',
                          ),
                        ),
                        CustomScrollView(
                          physics: AlwaysScrollableScrollPhysics(),
                          controller: scrollController,
                          slivers: [
                            // SliverPadding(padding: EdgeInsets.only(top: top)),
                            SliverPersistentHeader(
                              delegate: HeaderDelegate(),
                              pinned: true,
                            ),
                            SliverToBoxAdapter(
                              child: Stack(
                                children: [
                                  Padding(
                                    padding: EdgeInsets.fromLTRB(
                                      0.px,
                                      0,
                                      0.px,
                                      0,
                                    ),
                                    child: Column(
                                      mainAxisAlignment:
                                          MainAxisAlignment.start,
                                      crossAxisAlignment:
                                          CrossAxisAlignment.start,
                                      children: [
                                        Padding(
                                          padding: EdgeInsets.fromLTRB(
                                            12.px,
                                            0,
                                            12.px,
                                            0,
                                          ),

                                          child: Column(
                                            mainAxisAlignment:
                                                MainAxisAlignment.start,
                                            crossAxisAlignment:
                                                CrossAxisAlignment.start,
                                            children: [
                                              hiSpace(height: 12),
                                              BannerWidget(
                                                isNetworkImg: true,
                                                autoPlay: true,
                                                isbanner: true,
                                                bannerListHome:
                                                    controller.bannerList,
                                              ),
                                              hiSpace(height: 16),
                                              VerticalScrollNoticeBar(
                                                showBoxBorder: false,
                                                messages: controller.noticeList,
                                                interval: const Duration(
                                                  seconds: 3,
                                                ),
                                                onPressed: (item) {
                                                  Get.toNamed(
                                                    NewsDetailPage.path,
                                                    arguments: {
                                                      'id': item.id,
                                                      'content': item.content,
                                                      'title': item.title,
                                                      'labelName':
                                                          item.labelName,
                                                      'createTime':
                                                          item.createTime,
                                                    },
                                                  );
                                                },
                                                onPressedRight: () {
                                                  Get.toNamed(
                                                    AnnouncementPage.path,
                                                  );
                                                },
                                              ),
                                              hiSpace(height: 22),
                                              Row(
                                                mainAxisAlignment:
                                                    MainAxisAlignment
                                                        .spaceAround,
                                                children: [
                                                  _barwidget(
                                                    txt: '新人手册',
                                                    url:
                                                        'static/images/home/pic1.png',
                                                    onTap:
                                                        () => Get.toNamed(
                                                          NewcomerHandbookPage
                                                              .path,
                                                        ),
                                                  ),
                                                  _barwidget(
                                                    txt: '邀请好友',
                                                    url:
                                                        'static/images/home/oic2.png',
                                                    onTap:
                                                        () => {
                                                          if (globalController
                                                                  .user
                                                                  .value!
                                                                  .bindFlag ==
                                                              true)
                                                            {
                                                              Get.toNamed(
                                                                MyFriendPage
                                                                    .path,
                                                              ), //已经填写邀请码
                                                            }
                                                          else
                                                            {
                                                              showInvitedSheet(), //还没填写邀请码
                                                            },
                                                        },
                                                  ),
                                                  _barwidget(
                                                    txt: '客服中心',
                                                    url:
                                                        'static/images/home/pic3.png',
                                                    onTap:
                                                        () => {
                                                          Get.toNamed(
                                                            CustomerServicePage
                                                                .path,
                                                          ),
                                                        },
                                                  ),
                                                  _barwidget(
                                                    txt: '活动中心',
                                                    url:
                                                        'static/images/home/pic4.png',
                                                    onTap:
                                                        () => {
                                                          showToast(
                                                            '活动即将上线，敬请期待',
                                                          ),
                                                        },
                                                  ),
                                                ],
                                              ),
                                              _midwidget(context: context),
                                            ],
                                          ),
                                        ),

                                        hiSpace(height: 6),
                                      ],
                                    ),
                                  ),
                                ],
                              ),
                            ),
                            SliverPersistentHeader(
                              delegate: HeaderDelegate2(),
                              pinned: true,
                            ),
                            if (controller.selectType.value == 'PLATFORM' &&
                                controller.homeList.isEmpty)
                              SliverToBoxAdapter(child: EmptyWidget()),
                            if (controller.selectType.value == 'BRAND' &&
                                controller.homeList.isEmpty)
                              SliverToBoxAdapter(child: EmptyWidget()),
                            if (controller.selectType.value == 'BLIND_BOX' &&
                                controller.homeList.isEmpty)
                              SliverToBoxAdapter(child: EmptyWidget()),
                            SliverList(
                              delegate: SliverChildBuilderDelegate(
                                childCount: controller.homeList.length,
                                (BuildContext context, int index) {
                                  return CollectionItemWidget(
                                    item: controller.homeList[index],
                                  );
                                },
                              ),
                            ),
                            SliverPadding(padding: EdgeInsets.only(bottom: 50.px)),
                          ],
                        ),
                      ],
                    ),
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  //中间区域
  _midwidget({required BuildContext context}) {
    return Container(
      width: context.width,
      color: Colors.transparent,
      padding: EdgeInsets.fromLTRB(0, 20.px, 0, 0.px),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          ImageAssetWidget(
            imageUrl: 'static/images/home/title1.png',
            width: 176.px,
            height: 47.px,
          ),
          // SizedBox(width: 8.px),
          // Text(
          //   '时空发售站',
          //   style: TextStyle(fontSize: 18.px, color: AppColors.fontColor),
          // ),
          // SizedBox(width: 8.px),
          // ImageAssetWidget(
          //   imageUrl: 'static/images/home/zuizi.png',
          //   width: 24.px,
          //   height: 24.px,
          // ),
        ],
      ),
    );
  }
  //自定义tab金刚区

  _barwidget({
    required String txt,
    required String url,
    required VoidCallback? onTap,
  }) {
    return GestureDetector(
      onTap: () {
        onTap!();
      },
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          ImageAssetWidget(imageUrl: url, width: 40.px, height: 40.px),
          hiSpace(height: 8),
          Text(
            txt,
            style: TextStyle(
              fontSize: 12,
              color: AppColors.backgroundColorGrey,
            ),
            overflow: TextOverflow.ellipsis,
          ),
        ],
      ),
    );
  }

  void _onChange(String value) {
    // controller.modeType.value = value;
    setState(() {
      // _selectType = value;
      controller.selectType.value = value;
      controller.getProductList();
    });
  }

  @override
  void dispose() {
    super.dispose();
    scrollController.dispose();
  }

  Future<void> _handleRefresh() async {
    controller.getProductList();
    controller.getBarnnerList();
    controller.getNoticeList();
    return;
  }
}
